package core

import (
	"blog_go/global"
	"bytes"
	"fmt"
	"github.com/sirupsen/logrus"
	"os"
	"path"
)

// 颜色
const (
	red    = 31
	yellow = 33
	blue   = 36
	gray   = 37
)

type LogFormatter struct{}

func (t *LogFormatter) Format(entry *logrus.Entry) ([]byte, error) {
	var levelColor int
	switch entry.Level {
	case logrus.DebugLevel, logrus.TraceLevel:
		levelColor = gray
	case logrus.WarnLevel:
		levelColor = yellow
	case logrus.ErrorLevel, logrus.FatalLevel, logrus.PanicLevel:
		levelColor = red
	default:
		levelColor = blue
	}
	var b *bytes.Buffer
	if entry.Buffer != nil {
		b = entry.Buffer
	} else {
		b = &bytes.Buffer{}
	}
	logger := global.Conf.Logger
	// 自定义时间格式
	format := entry.Time.Format("2006-01-02 15:04:05")
	if entry.HasCaller() {
		// 自定义文件路劲
		function := entry.Caller.Function
		sprintf := fmt.Sprintf("%s:%d", path.Base(entry.Caller.File), entry.Caller.Line)
		// 自定义输出格式
		fmt.Fprintf(b, "%s[%s] \x1b[%dm[%s]\x1b[0m %s %s %s\n", logger.Prefix, format, levelColor, entry.Level, sprintf, function, entry.Message)
	} else {
		fmt.Fprintf(b, "%s[%s] \x1b[%dm[%s]\x1b[0m %s\n", logger.Prefix, format, levelColor, entry.Level, entry.Message)
	}
	return b.Bytes(), nil
}

func InitLogger() *logrus.Logger {
	level, err := logrus.ParseLevel(global.Conf.Logger.Level)
	if err != nil {
		level = logrus.InfoLevel
	}

	logger := logrus.New()                              // 新建一个实例
	logger.SetOutput(os.Stdout)                         // 设置输出类型
	logger.SetReportCaller(global.Conf.Logger.ShowLine) // 开启反回函数名和行号
	logger.SetFormatter(&LogFormatter{})                // 设置自己自定义的format
	logger.SetLevel(level)                              // 设置最低的level
	//file, err := os.OpenFile(global.Config.Logger.Director, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
	//multiWriter := io.MultiWriter(file, os.Stdout)
	//logger.SetOutput(multiWriter) // 设置输出位置
	global.Log = logger
	// 开启全局默认的日志自定义
	InitDefaultLogger()
	return logger
}

func InitDefaultLogger() {
	level, err := logrus.ParseLevel(global.Conf.Logger.Level)
	if err != nil {
		level = logrus.InfoLevel
	}

	// 设置全局默认的logrus
	logrus.SetOutput(os.Stdout)                         // 设置输出类型
	logrus.SetReportCaller(global.Conf.Logger.ShowLine) // 开启反回函数名和行号
	logrus.SetFormatter(&LogFormatter{})                // 设置自己自定义的format
	logrus.SetLevel(level)                              // 设置最低的level
	//file, err := os.OpenFile(global.Config.Logger.Director, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
	//multiWriter := io.MultiWriter(file, os.Stdout)
	//logrus.SetOutput(multiWriter)                         // 设置输出位置
}

type TraceIdHook struct {
	TraceId string
}

func NewTraceIdHook(traceId string) logrus.Hook {
	hook := TraceIdHook{
		TraceId: traceId,
	}
	return &hook
}

func (hook *TraceIdHook) Fire(entry *logrus.Entry) error {
	entry.Data["trace_id"] = hook.TraceId
	return nil
}

func (hook *TraceIdHook) Levels() []logrus.Level {
	return logrus.AllLevels
}
